package se.padev.si.application;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;


import android.os.Bundle;
import android.widget.TabHost;

import ioio.lib.api.Uart;
import ioio.lib.api.exception.ConnectionLostException;
import ioio.lib.util.AbstractIOIOActivity;
 

public class SIComActivity extends AbstractIOIOActivity  {
	
	private Uart uart; 
    private InputStream in; 
    private OutputStream out;
    private TabHost mTabHost;
    
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
            super.onCreate(savedInstanceState); 
            setContentView(R.layout.main); 
            
            mTabHost = (TabHost)findViewById(android.R.id.tabhost);
            mTabHost.setup();
            
            mTabHost.addTab(mTabHost.newTabSpec("tab_main").setIndicator(getResources().getText(R.string.main), getResources().getDrawable(R.drawable.info_2)).setContent(R.id.mainTab));
            mTabHost.addTab(mTabHost.newTabSpec("tab_read").setIndicator(getResources().getText(R.string.read), getResources().getDrawable(R.drawable.download_2)).setContent(R.id.readTab));
            mTabHost.addTab(mTabHost.newTabSpec("tab_write").setIndicator(getResources().getText(R.string.write), getResources().getDrawable(R.drawable.upload_2)).setContent(R.id.writeTab));
            
            mTabHost.setCurrentTab(0);
    } 
    
    class IOIOThread extends AbstractIOIOActivity.IOIOThread { 
    	
    	Boolean imBusy = false; 
    	private int bufferSize = 1000; 
    	private Boolean waitingForETX = false;
    	private byte[] message = new byte[bufferSize];
    	private int messageIndex = 0;
    	
    	private static final int INPIN 	= 4;
    	private static final int OUTPIN = 5;
    	private static final int BAUD 	= 2400;
    	
    	private static final byte STX 	= 0x02;
    	private static final byte ETX 	= 0x03;
    	
    	@Override 
        protected void setup() throws ConnectionLostException { 
    		try { 
    			uart = ioio_.openUart(INPIN, OUTPIN, BAUD, Uart.Parity.NONE, Uart.StopBits.ONE); 
                in = uart.getInputStream();
                out = uart.getOutputStream();
    		} 
			catch(ConnectionLostException e) 
			{ 
			    // iWrite(e.getMessage()); 
				// iWrite(Log.getStackTraceString(e)); 
			} 
        } 
    
    	@Override 
        protected void loop() throws ConnectionLostException { 
    		if(!imBusy) 
            { 
	            imBusy = true; 
	            checkData();
            } 
        }
    	
    	private void checkData() {	
	    	try { 
	    		int availableBytes =in.available(); 
	    		if (availableBytes > 0) { 
	    			byte[] readBuffer = new byte[bufferSize]; 
	                in.read(readBuffer, 0, availableBytes);
	                int start = findByte(readBuffer, availableBytes, STX);
	                int stop = findByte(readBuffer, availableBytes, ETX);
	                
	                if (start < availableBytes)
	                {
	                	messageIndex = 0;
                		for (int index = start + 1; index < stop; index++)
                			message[messageIndex++] = readBuffer[index];
	                	if (stop < availableBytes)
	                	{
	                		// TODO: parse message!
	                	}
	                	else
	                		waitingForETX = true;
	                }
	                else if (waitingForETX)
	                {
	                	for (int index = 0; index < stop; index++)
                			message[messageIndex++] = readBuffer[index];
	                	if (stop < availableBytes)
	                	{
	                		// TODO: parse message!
	                		waitingForETX = false;
	                	}
	                }
	    		} 
	    		sleep(500); 
	    	} catch (InterruptedException e) { 
	    		//iWrite("Error: " +e ); 
	    	} catch (IOException e) { 
	    		// TODO Auto-generated catch block 
	            // 
	            // iWrite("Error: " +e );e.printStackTrace(); 
	    	} 
	    	imBusy = false; 
    	}
    	
    	private int findByte(byte[] inBuffer, int length, byte data) {
    		for (int index = 0; index < length; index++)
    		{
    			if (inBuffer[index] == data)
    				return index;
    		}
    		return length;
    	}
	}
    
    @Override 
    protected AbstractIOIOActivity.IOIOThread createIOIOThread() { 
		return new IOIOThread(); 
	}
}
    	